/**
 * 
 */
package com.jdy.haoduoai.adapter;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.event.OnMediaResendEvent;
import com.jdy.haoduoai.util.CircleTransform;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.Tools;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import static com.jdy.haoduoai.enums.PosterType.Turing;

/**
 * @author zp 2016-5-18 下午5:24:06
 */
public class SpeakWordHistoryAdapter extends BaseAdapter {

  private final Activity mContext;

  private final List<SpeakForYouItem> wordList;

  private final LayoutInflater mInflater;

  private final SparseArray<View> mSArray;

  private final Uri BabyUri;

  private final Uri ParentUri;

  public SpeakWordHistoryAdapter(Activity context,
      List<SpeakForYouItem> wordList) {
    this.mContext = context;

    this.wordList = wordList;

    this.mInflater = LayoutInflater.from(mContext);

    mSArray = new SparseArray<View>();

    SharedPreferences prefs = this.mContext.getSharedPreferences(
        Constant.USER_INFO, Context.MODE_PRIVATE);

    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");

    this.BabyUri = Uri.parse(babyImagePath);

    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");

    this.ParentUri = Uri.parse(parentImagePath);

  }

  /*
   * (non-Javadoc)
   * 
   * @see android.widget.Adapter#getCount()
   */
  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return wordList.size();
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.widget.Adapter#getItem(int)
   */
  @Override
  public Object getItem(int position) {
    // TODO Auto-generated method stub
    return wordList.get(position);
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.widget.Adapter#getItemId(int)
   */
  @Override
  public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.widget.Adapter#getView(int, android.view.View,
   * android.view.ViewGroup)
   */
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    ViewHolder holder;
    convertView = mSArray.get(position);
    final SpeakForYouItem sfyi = wordList.get(position);

    holder = new ViewHolder();
    if (convertView == null) {
      switch (sfyi.SFYType) {
      case TEXT:
        if (sfyi.posterType.equals(Turing)) {
          convertView = mInflater.inflate(
              R.layout.turing_speak_history_list_item, null);
        } else {
          convertView = mInflater.inflate(R.layout.speak_history_list_item,
              null);
          holder.speakLayout = (com.jdy.haoduoai.view.SquareLayout) convertView
              .findViewById(R.id.speak_slayout);
        }
        holder.timestampTv = (TextView) convertView
            .findViewById(R.id.timestamp);
        holder.avatarImg = (ImageView) convertView
            .findViewById(R.id.avatar_img);
        holder.contentTV = (TextView) convertView.findViewById(R.id.record_tv);
        holder.coverImg = (ImageView) convertView.findViewById(R.id.story_img);
        holder.errorIconImg = (ImageView) convertView
            .findViewById(R.id.send_error_img);
        holder.pBar = (ProgressBar) convertView
            .findViewById(R.id.sending_progressbar);
        break;
      case VIDEO:

        convertView = mInflater.inflate(R.layout.speak_history_list_item, null);
        holder.timestampTv = (TextView) convertView
            .findViewById(R.id.timestamp);
        holder.speakLayout = (com.jdy.haoduoai.view.SquareLayout) convertView
            .findViewById(R.id.speak_slayout);
        holder.avatarImg = (ImageView) convertView
            .findViewById(R.id.avatar_img);
        holder.contentTV = (TextView) convertView.findViewById(R.id.record_tv);
        holder.coverImg = (ImageView) convertView.findViewById(R.id.story_img);
        holder.errorIconImg = (ImageView) convertView
            .findViewById(R.id.send_error_img);
        holder.pBar = (ProgressBar) convertView
            .findViewById(R.id.sending_progressbar);

        break;
      case VOICE:
        convertView = mInflater.inflate(R.layout.row_received_voice, null);
        holder.timestampTv = (TextView) convertView
            .findViewById(R.id.timestamp);
        holder.avatarImg = (ImageView) convertView
            .findViewById(R.id.iv_userhead);
        holder.coverImg = (ImageView) convertView.findViewById(R.id.iv_voice);
        holder.pBar = (ProgressBar) convertView.findViewById(R.id.pb_receiving);
        holder.errorIconImg = (ImageView) convertView
            .findViewById(R.id.imageview_rereceiving);
        holder.timeLengthTv = (TextView) convertView
            .findViewById(R.id.tv_length);
        holder.unreadImg = (ImageView) convertView
            .findViewById(R.id.iv_unread_voice);

        break;
      }

      convertView.setTag(holder);
      mSArray.put(position, convertView);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    switch (sfyi.SFYType) {

    case TEXT:
      if (holder.speakLayout != null) {
        if (!sfyi.posterType.equals(Turing)) {
          holder.speakLayout.setVisibility(View.GONE);
          if (Tools.isNotEmpty(ParentUri)) {
            Picasso
                .with(mContext)
                .load(ParentUri)
                .placeholder(
                    mContext.getResources().getDrawable(
                        R.drawable.default_discussion_avatar))
                .error(
                    mContext.getResources().getDrawable(
                        R.drawable.default_discussion_avatar))
                .transform(new CircleTransform()).into(holder.avatarImg);
          }
        }
      }
      break;
    case VIDEO:
      if (holder.speakLayout != null) {
        holder.speakLayout.setVisibility(View.VISIBLE);
      }

      if (Tools.isNotEmpty(sfyi.Src)) {
        Picasso
            .with(mContext)
            .load(sfyi.Src)
            .fit()
            .centerCrop()
            .placeholder(
                mContext.getResources().getDrawable(R.drawable.default_cover))
            .error(
                mContext.getResources().getDrawable(R.drawable.default_cover))
            .into(holder.coverImg);
      }

      switch (sfyi.posterType) {
      case Parent:

        if (Tools.isNotEmpty(ParentUri)) {
          Picasso
              .with(mContext)
              .load(ParentUri)
              .placeholder(
                  mContext.getResources().getDrawable(
                      R.drawable.default_discussion_avatar))
              .error(
                  mContext.getResources().getDrawable(
                      R.drawable.default_discussion_avatar))
              .transform(new CircleTransform()).into(holder.avatarImg);
        }
        break;
      case Turing:
        if (holder.avatarImg != null)
          holder.avatarImg.setImageResource(R.drawable.default_turning_avatar);
        break;
      default:
        break;
      }

      break;
    case VOICE:

      if (Tools.isNotEmpty(sfyi.length)
          && Tools.isNotEmpty(holder.timeLengthTv))
        holder.timeLengthTv.setText(String.format("%s\"", sfyi.length));
      if (holder.unreadImg != null) {
        if (sfyi.hasRead) {
          holder.unreadImg.setVisibility(View.GONE);
        } else {
          holder.unreadImg.setVisibility(View.VISIBLE);
        }
        holder.coverImg.setOnClickListener(new VoicePlayClickListener(sfyi,
            this, holder.errorIconImg, holder.coverImg, mContext, holder.pBar,
            holder.unreadImg));
      }

      if (Tools.isNotEmpty(BabyUri)) {
        Picasso
            .with(mContext)
            .load(BabyUri)
            .placeholder(
                mContext.getResources().getDrawable(
                    R.drawable.default_discussion_avatar))
            .error(
                mContext.getResources().getDrawable(
                    R.drawable.default_discussion_avatar))
            .transform(new CircleTransform()).into(holder.avatarImg);
      }
      break;
    default:
      break;
    }

    if (holder.contentTV != null) {

      if (sfyi.posterType.equals(Turing)) {
        holder.contentTV.setText(Tools.unicodeToString(sfyi.Caption));
      } else {
        holder.contentTV.setText(sfyi.Caption);
      }

      holder.contentTV.setOnLongClickListener(new OnLongClickListener() {

        @SuppressWarnings("deprecation")
        @Override
        public boolean onLongClick(View v) {
          ClipboardManager cmb = (ClipboardManager) mContext
              .getSystemService(Context.CLIPBOARD_SERVICE);
          cmb.setText(sfyi.Caption);

          CommonUtil.showToask(mContext, "文字已复制到剪贴板~");

          return true;
        }
      });
    }

    holder.errorIconImg.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        EventBus.getDefault().post(new OnMediaResendEvent(sfyi));
      }
    });

    // Handle the state of sending messsage
    switch (sfyi.State) {
    case FAILED:
      holder.errorIconImg.setVisibility(View.VISIBLE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case NONE:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case SUCCESS:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    case SENDING:
      holder.pBar.setVisibility(View.VISIBLE);
      break;
    default:
      holder.errorIconImg.setVisibility(View.GONE);
      holder.pBar.setVisibility(View.GONE);
      break;
    }
    if (position == 0) {
      holder.timestampTv.setText(DateUtils.convert2ShortFormat(sfyi.createAt));
      holder.timestampTv.setVisibility(View.VISIBLE);
    } else {
      SpeakForYouItem lastSfyi = wordList.get(position - 1);
      if (DateUtils.isCloseEnough(sfyi.createAt, lastSfyi.createAt)) {
        holder.timestampTv.setVisibility(View.GONE);
      } else {
        holder.timestampTv
            .setText(DateUtils.convert2ShortFormat(sfyi.createAt));
        holder.timestampTv.setVisibility(View.VISIBLE);
      }
    }

    return convertView;
  }

  private class ViewHolder {
    TextView timestampTv;
    ImageView avatarImg;
    TextView contentTV;
    com.jdy.haoduoai.view.SquareLayout speakLayout;
    ImageView coverImg;
    ImageView errorIconImg;
    ProgressBar pBar;
    TextView timeLengthTv;
    ImageView unreadImg;
  }

}
